package com.guaoran.source.mybatis.v2.statement;

import com.guaoran.source.mybatis.v2.config.Configuration;
import com.guaoran.source.mybatis.v2.datasource.DataSource;
import com.guaoran.source.mybatis.v2.mapper.MapperRegistry;
import com.guaoran.source.mybatis.v2.result.ResultSetHandler;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.List;

/**
 * @author : 孤傲然
 * @Description :
 * @date :2018/5/26 12:44
 */
public class StatementHandler {
    private Configuration configuration;
    private ResultSetHandler resultSetHandler;

    public StatementHandler(Configuration configuration) {
        this.configuration = configuration;
        this.resultSetHandler = new ResultSetHandler();
    }

    public <T> T query(MapperRegistry.KnownMappersInfo knownMappersInfo, Object paramment) throws SQLException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        List<T> resultList = this.<T>queryList(knownMappersInfo, paramment);
        if(resultList!=null && resultList.size()>0){
            return resultList.get(0);
        }
        return null;
    }

    public <T> List<T> queryList(MapperRegistry.KnownMappersInfo knownMappersInfo, Object paramment) throws SQLException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Connection connection = getConnection();
        String sql = knownMappersInfo.getSql()+String.valueOf(paramment==null?"":paramment);
        System.out.println(sql);
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        return resultSetHandler.handle(resultSet,knownMappersInfo.getType());
    }
    public Connection getConnection() throws SQLException {
        //从configuration中取数据源
        DataSource dataSource = configuration.getDataSource();
        Connection conn = null;
        try {
            Class.forName(dataSource.getDriver()); //classLoader,加载对应驱动
            conn = DriverManager.getConnection(dataSource.getUrl(), dataSource.getUsername(), dataSource.getPassword());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}
